import React, { useEffect, useState } from 'react';
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

const TestSockJS: React.FC = () => {
  const [messages, setMessages] = useState<string[]>([]);
  const [stompClient, setStompClient] = useState<Stomp.Client | null>(null);

  useEffect(() => {
    // 创建 WebSocket 连接
    const socket = new SockJS('http://192.188.123.2:4399/ws');
    const client = Stomp.over(socket);
    let subscription: Stomp.Subscription | null = null;

    // 连接后订阅消息
    client.connect({}, (frame) => {
      console.log('Connected: ' + frame);
      subscription = client.subscribe('/broadcast/test', (message) => {
        setMessages((prevMessages) => {
          // 检查是否已存在消息，避免重复添加
          if (!prevMessages.includes(message.body)) {
            return [...prevMessages, message.body];
          }
          return prevMessages;
        });
      });
    });

    setStompClient(client);

    // 清理 WebSocket 连接和订阅
    return () => {
      if (subscription) {
        subscription.unsubscribe();
      }
      if (client.connected) {
        client.disconnect(() => {
          console.log('Disconnected');
        });
      }
    };
  }, []); // 确保只在组件挂载时执行

  // 发送消息
  const sendMessage = () => {
    if (stompClient && stompClient.connected) {
      stompClient.send('/send/hello', {}, 'Hello, this is a test message!');
    } else {
      console.warn('Stomp client is not connected.');
    }
  };

  return (
    <div>
      <h1>WebSocket Client</h1>
      <div id="messages">
        {messages.map((message, index) => (
          <div key={index}>{message}</div>
        ))}
      </div>
      <button onClick={sendMessage}>Send Message</button>
    </div>
  );
};

export default TestSockJS;
